<?php

//接收参数
$json = json_decode(file_get_contents('php://input'), true);
$prName = $json['repository']['name'] ?? 'xiaoyu-live';
$branch = htmlspecialchars($_GET['branch'] ?? 'develop');
$json['project']['http_url'] = $json['project']['http_url'] ?? 'http://192.168.41.222/server/xiaoyu-live.git';


echo "即将更新项目:$prName,分支:$branch" . PHP_EOL;

//记录请求信息
file_put_contents('request.txt', json_encode($json));

//验证合法性，并返回路径
$fullPath = pathIsExist($prName, $json, $branch);


//执行更新
$data = system("cd $fullPath &&  git pull origin $branch:$branch");
if (empty($data)) {
    system("cd {$_SERVER['DOCUMENT_ROOT']} && echo '$data' >> errorupdate.log ");
    errorExitAndLog('更新失败!');
}

//写入日志
errorExitAndLog($data, false);

//合法性验证
function pathIsExist($prName, $json, $branch)
{

    //获取当前目录
    $path = dirname(exec('pwd'));
    $fullePath = $path . '/' . $prName;

    //判断目录是否存在
    if (!file_exists($fullePath)) {
        echo "{$fullePath}目录不存在,即将自动克隆项目" . PHP_EOL;
        autoClonePr($json, $fullePath, $branch);
    } elseif (strpos($json['ref'], $branch) === false) {
        //如果URL中的分支名与推送的不一致，将直接退出
        errorExitAndLog("push的分支名{$json['ref']}与要更新的分支名{$branch}不一致，即将退出") . PHP_EOL;
    }

    return $fullePath;
}

//自动克隆项目
function autoClonePr($json, $fullePath, $branch)
{
    $newHttpUrl = str_replace('http://', "http://DeployRobot:offcn.com@", $json['project']['http_url']);
    echo "即将执行命令:git clone $newHttpUrl $fullePath" . PHP_EOL;
    system("git clone $newHttpUrl $fullePath  &&  echo '克隆代码完成,即将切换分支到{$branch}\n' && cd {$fullePath}  && git checkout {$branch}");
}


//判断项目是否存在
function projectIsExist($prName)
{
    //定义可以更新那几个目录
    $prArr = [
        'xiaoyu-live' => 'xiaoyu-live',
        'media-server-manager' => 'media-server-manager',
        'media-server-api' => 'media-server-api',
    ];
    //如果不存在，则放弃
    if (!isset($prArr[$prName])) {
        errorExitAndLog("<{$prArr[$prName]}>项目不存在");
    }
}


function errorExitAndLog($remark, $isDie = true)
{
    //转换成字符串
    $remark = is_string($remark) ? $remark : json_encode($remark);
    //记录日志
    $handle = fopen('errorLog.txt', "a+");
    fwrite($handle, $remark . "\n");
    fclose($handle);

    //退出
    if ($isDie) {
        die($remark);
    }
}